package cn.easyplatform.studio.cmd.link;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.utils.GlobalVariableService;
import cn.easyplatform.studio.vos.LinkVo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UpdateLinkListCmd extends LinkCmd implements Command<Boolean> {
    private List<LinkVo> linkVos;
    private String deleteEntityId;
    public UpdateLinkListCmd(List<LinkVo> linkVos, String deleteEntityId)
    {
        this.linkVos = linkVos;
        this.deleteEntityId = deleteEntityId;
    }
    @Override
    public Boolean execute(CommandContext cc) {
        if (linkVos == null || linkVos.size() == 0 || Strings.isBlank(deleteEntityId))
            return false;
        for (LinkVo linkVo: linkVos) {
            linkVo.setUpdateUser(cc.getUser().getUserId());
            linkVo.setUpdateDate(new Date());
        }

        boolean isSuccess = cc.getLink().updateLinks("ep_" + cc.getProject().getId() + "_link", linkVos);
        if (isSuccess == false)
            return false;
        return updateValidation(cc);
    }

    protected Boolean updateValidation(CommandContext cc)
    {
        List<LinkVo> updateVos = cc.getLink().getLinkWithChildrenEntityId("ep_"+cc.getProject().getId()+"_link", deleteEntityId);
        if (updateVos == null || updateVos.size() == 0)
            return false;
        //更换数据表缓存
        synchronized (GlobalVariableService.getInstance().getDataLinkVoList()) {
            //List<LinkVo> linkVos = GlobalVariableService.getInstance().getDataLinkVoList();
            //List<LinkVo> treeVoList = GlobalVariableService.getInstance().getLinkVoList();
            List<Integer> updateList = new ArrayList<>();
            for (LinkVo updateVo: updateVos) {
                boolean isSearch = false;
                for (int i = 0; i < GlobalVariableService.getInstance().getDataLinkVoList().size(); i++) {
                    LinkVo vo = GlobalVariableService.getInstance().getDataLinkVoList().get(i);
                    if (updateVo.getEntityId().equals(vo.getEntityId())) {
                        updateList.add(i);
                        isSearch = true;
                        break;
                    }
                }
                if (isSearch == false)
                    updateList.add(-1);
            }

            if (updateList != null && updateList.size() != 0)
            {
                for (int i = 0; i < updateList.size(); i++) {
                    GlobalVariableService.getInstance().getDataLinkVoList().set(updateList.get(i), updateVos.get(i));
                }
                GlobalVariableService.getInstance().getLinkVoList().clear();
            }
            return true;
        }
    }
}
